package com.example.abbitmqtest.service.impl;

import com.example.abbitmqtest.config.RabbitConfig;
import com.example.abbitmqtest.entity.Order;
import com.example.abbitmqtest.mapper.OrderMapper;
import com.example.abbitmqtest.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Order createOrder(Order order) {
        order.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        order.setStatus(0);
        order.setCreateTime(LocalDateTime.now());
        
        // 保存订单
        orderMapper.insert(order);
        
        // 发送延迟消息，用于订单超时取消
//        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_DELAY_EXCHANGE,
//                RabbitConfig.ORDER_DELAY_ROUTING_KEY,
//                order.getOrderNo());

        // 定义延迟时间，这里设置为 1 分钟（单位：毫秒）
        long delayTime = 60 * 1000;

        // 发送延迟消息，用于订单超时取消
        rabbitTemplate.convertAndSend(RabbitConfig.ORDER_DELAY_EXCHANGE,
                RabbitConfig.ORDER_DELAY_ROUTING_KEY,
                order.getOrderNo(),
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) {
                        // 设置消息的延迟时间
                        message.getMessageProperties().setHeader("x-delay", delayTime);
                        return message;
                    }
                });


        return order;
    }

    @Override
    public boolean payOrder(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null && order.getStatus() == 0) {
            order.setStatus(1);
            order.setPayTime(LocalDateTime.now());
            return orderMapper.update(order) > 0;
        }
        return false;
    }

    @Override
    public boolean cancelOrder(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null && order.getStatus() == 0) {
            order.setStatus(2);
            order.setCancelTime(LocalDateTime.now());
            return orderMapper.update(order) > 0;
        }
        return false;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }
}